package com.fivefu.core.hik.services.impl;

import com.alibaba.fastjson.JSON;
import com.fivefu.base.common.utils.str.StrUtils;
import com.fivefu.core.hik.config.HikPreviewConfig;
import com.fivefu.core.hik.dto.response.ResponseResult;
import com.fivefu.core.hik.properties.HikProperties;
import com.fivefu.core.hik.services.DbHikInterfaceService;
import com.fivefu.core.hik.services.HikvisionService;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 海康数据对接
 */
@Service
public class HikvisionServiceImpl implements HikvisionService {

    //设置OpenAPI接口的上下文
    private static final String ARTEMIS_PATH = "/artemis";

    @Autowired
    private DbHikInterfaceService dbHikInterfaceService;
    @Autowired
    private HikProperties hikProperties;

    /**
     * 请求海康接口数据
     * @param url 接口地址
     * @param body 请求参数
     * @param stime 开始时间
     * @param etime 结束时间
     * @param type 查询类型
     * @return
     */
    @Override
    public ResponseResult doPostString(String url, String body, LocalDateTime stime, LocalDateTime etime, String type) {
        //设置接口的URI地址
        final String previewURLsApi = ARTEMIS_PATH + url;
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                if (hikProperties.getUseSSL() != null && hikProperties.getUseSSL()){
                    put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
                }else{
                    put("http://", previewURLsApi);//根据现场环境部署确认是http还是https
                }
            }
        };

        //设置参数提交方式
        String contentType = "application/json";

        //新增请求记录
        Long interfaceID = dbHikInterfaceService.insertHikInterface(url, body, stime, etime, type);

        //调用接口
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType , null);// post请求application/json类型参数
        ResponseResult responseResult = null;
        if (StrUtils.isNotNull(result) && !result.startsWith("<")){
            //解析返回结果
            responseResult = JSON.parseObject(result, ResponseResult.class);

            //复制结果信息
            ResponseResult interfaceResult = new ResponseResult();
            BeanUtils.copyProperties(responseResult, interfaceResult);

            Integer interfaceStatus = 0;
            if ("0".equals(responseResult.getCode())){//返回成功
                interfaceStatus = 1;

                //不保存数据
                interfaceResult.setData(null);
            }
            dbHikInterfaceService.updateHikInterfaceStatus(interfaceID, JSON.toJSONString(interfaceResult), interfaceStatus);

        }else{
            dbHikInterfaceService.updateHikInterfaceStatus(interfaceID, "海康接口调用异常", 0);
        }
        return responseResult;
    }
}
